home *** CD-ROM | disk | FTP | other *** search
/ Aminet 34 / Aminet 34 (2000)(Schatztruhe)[!][Dec 1999].iso / Aminet / dev / lang / Python152_Src.lha / Python152_Source / Python / import.c < prev    next >
Encoding:
C/C++ Source or Header  |  1999-04-27  |  55.7 KB  |  2,455 lines

  1. /***********************************************************
  2. Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam,
  3. The Netherlands.
  4.  
  5.                         All Rights Reserved
  6.  
  7. Permission to use, copy, modify, and distribute this software and its
  8. documentation for any purpose and without fee is hereby granted,
  9. provided that the above copyright notice appear in all copies and that
  10. both that copyright notice and this permission notice appear in
  11. supporting documentation, and that the names of Stichting Mathematisch
  12. Centrum or CWI or Corporation for National Research Initiatives or
  13. CNRI not be used in advertising or publicity pertaining to
  14. distribution of the software without specific, written prior
  15. permission.
  16.  
  17. While CWI is the initial source for this software, a modified version
  18. is made available by the Corporation for National Research Initiatives
  19. (CNRI) at the Internet address ftp://ftp.python.org.
  20.  
  21. STICHTING MATHEMATISCH CENTRUM AND CNRI DISCLAIM ALL WARRANTIES WITH
  22. REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF
  23. MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH
  24. CENTRUM OR CNRI BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL
  25. DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
  26. PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
  27. TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
  28. PERFORMANCE OF THIS SOFTWARE.
  29.  
  30. ******************************************************************/
  31.  
  32. /* Module definition and import implementation */
  33.  
  34. #include "Python.h"
  35.  
  36. #include "node.h"
  37. #include "token.h"
  38. #include "errcode.h"
  39. #include "marshal.h"
  40. #include "compile.h"
  41. #include "eval.h"
  42. #include "osdefs.h"
  43. #include "importdl.h"
  44. #ifdef macintosh
  45. #include "macglue.h"
  46. #endif
  47.  
  48. #ifdef HAVE_UNISTD_H
  49. #include <unistd.h>
  50. #endif
  51.  
  52. /* We expect that stat exists on most systems.
  53.    It's confirmed on Unix, Mac and Windows.
  54.    If you don't have it, add #define DONT_HAVE_STAT to your config.h. */
  55. #ifndef DONT_HAVE_STAT
  56. #define HAVE_STAT
  57.  
  58. #ifndef DONT_HAVE_SYS_TYPES_H
  59. #include <sys/types.h>
  60. #endif
  61. #ifndef DONT_HAVE_SYS_STAT_H
  62. #include <sys/stat.h>
  63. #endif
  64.  
  65. #ifdef _AMIGA
  66. #include <proto/dos.h>
  67. #endif
  68. #include "protos/import.h"
  69.  
  70. #if defined(PYCC_VACPP)
  71. /* VisualAge C/C++ Failed to Define MountType Field in sys/stat.h */
  72. #define S_IFMT (S_IFDIR|S_IFCHR|S_IFREG)
  73. #endif
  74.  
  75. #ifndef S_ISDIR
  76. #define S_ISDIR(mode) (((mode) & S_IFMT) == S_IFDIR)
  77. #endif
  78.  
  79. #endif
  80.  
  81.  
  82. extern long PyOS_GetLastModificationTime Py_PROTO((char*path, FILE *fp)); /* In getmtime.c */
  83.  
  84. /* Magic word to reject .pyc files generated by other Python versions */
  85. /* Change for each incompatible change */
  86. /* The value of CR and LF is incorporated so if you ever read or write
  87.    a .pyc file in text mode the magic number will be wrong; also, the
  88.    Apple MPW compiler swaps their values, botching string constants */
  89. /* XXX Perhaps the magic number should be frozen and a version field
  90.    added to the .pyc file header? */
  91. /* New way to come up with the magic number: (YEAR-1995), MONTH, DAY */
  92. #define MAGIC (20121 | ((long)'\r'<<16) | ((long)'\n'<<24))
  93.  
  94. /* See _PyImport_FixupExtension() below */
  95. static PyObject *extensions = NULL;
  96.  
  97. /* This table is defined in config.c: */
  98. extern struct _inittab _PyImport_Inittab[];
  99.  
  100. struct _inittab *PyImport_Inittab = _PyImport_Inittab;
  101.  
  102. /* Initialize things */
  103.  
  104. void
  105. _PyImport_Init()
  106. {
  107.     if (Py_OptimizeFlag) {
  108.         /* Replace ".pyc" with ".pyo" in import_filetab */
  109.         struct filedescr *p;
  110.         for (p = _PyImport_Filetab; p->suffix != NULL; p++) {
  111.             if (strcmp(p->suffix, ".pyc") == 0)
  112.                 p->suffix = ".pyo";
  113.         }
  114.     }
  115. }
  116.  
  117. void
  118. _PyImport_Fini()
  119. {
  120.     Py_XDECREF(extensions);
  121.     extensions = NULL;
  122. }
  123.  
  124.  
  125. /* Locking primitives to prevent parallel imports of the same module
  126.    in different threads to return with a partially loaded module.
  127.    These calls are serialized by the global interpreter lock. */
  128.  
  129. #ifdef WITH_THREAD
  130.  
  131. #include "pythread.h"
  132.  
  133. static PyThread_type_lock import_lock = 0;
  134. static long import_lock_thread = -1;
  135. static int import_lock_level = 0;
  136.  
  137. static void
  138. lock_import()
  139. {
  140.     long me = PyThread_get_thread_ident();
  141.     if (me == -1)
  142.         return; /* Too bad */
  143.     if (import_lock == NULL)
  144.         import_lock = PyThread_allocate_lock();
  145.     if (import_lock_thread == me) {
  146.         import_lock_level++;
  147.         return;
  148.     }
  149.     if (import_lock_thread != -1 || !PyThread_acquire_lock(import_lock, 0)) {
  150.         PyThreadState *tstate = PyEval_SaveThread();
  151.         PyThread_acquire_lock(import_lock, 1);
  152.         PyEval_RestoreThread(tstate);
  153.     }
  154.     import_lock_thread = me;
  155.     import_lock_level = 1;
  156. }
  157.  
  158. static void
  159. unlock_import()
  160. {
  161.     long me = PyThread_get_thread_ident();
  162.     if (me == -1)
  163.         return; /* Too bad */
  164.     if (import_lock_thread != me)
  165.         Py_FatalError("unlock_import: not holding the import lock");
  166.     import_lock_level--;
  167.     if (import_lock_level == 0) {
  168.         import_lock_thread = -1;
  169.         PyThread_release_lock(import_lock);
  170.     }
  171. }
  172.  
  173. #else
  174.  
  175. #define lock_import()
  176. #define unlock_import()
  177.  
  178. #endif
  179.  
  180. /* Helper for sys */
  181.  
  182. PyObject *
  183. PyImport_GetModuleDict()
  184. {
  185.     PyInterpreterState *interp = PyThreadState_Get()->interp;
  186.     if (interp->modules == NULL)
  187.         Py_FatalError("PyImport_GetModuleDict: no module dictionary!");
  188.     return interp->modules;
  189. }
  190.  
  191.  
  192. /* List of names to clear in sys */
  193. static char* sys_deletes[] = {
  194.     "path", "argv", "ps1", "ps2", "exitfunc",
  195.     "exc_type", "exc_value", "exc_traceback",
  196.     "last_type", "last_value", "last_traceback",
  197.     NULL
  198. };
  199.  
  200. static char* sys_files[] = {
  201.     "stdin", "__stdin__",
  202.     "stdout", "__stdout__",
  203.     "stderr", "__stderr__",
  204.     NULL
  205. };
  206.  
  207.  
  208. /* Un-initialize things, as good as we can */
  209.  
  210. void
  211. PyImport_Cleanup()
  212. {
  213.     int pos, ndone;
  214.     char *name;
  215.     PyObject *key, *value, *dict;
  216.     PyInterpreterState *interp = PyThreadState_Get()->interp;
  217.     PyObject *modules = interp->modules;
  218.  
  219.     if (modules == NULL)
  220.         return; /* Already done */
  221.  
  222.     /* Delete some special variables first.  These are common
  223.        places where user values hide and people complain when their
  224.        destructors fail.  Since the modules containing them are
  225.        deleted *last* of all, they would come too late in the normal
  226.        destruction order.  Sigh. */
  227.  
  228.     value = PyDict_GetItemString(modules, "__builtin__");
  229.     if (value != NULL && PyModule_Check(value)) {
  230.         dict = PyModule_GetDict(value);
  231.         if (Py_VerboseFlag)
  232.             PySys_WriteStderr("# clear __builtin__._\n");
  233.         PyDict_SetItemString(dict, "_", Py_None);
  234.     }
  235.     value = PyDict_GetItemString(modules, "sys");
  236.     if (value != NULL && PyModule_Check(value)) {
  237.         char **p;
  238.         PyObject *v;
  239.         dict = PyModule_GetDict(value);
  240.         for (p = sys_deletes; *p != NULL; p++) {
  241.             if (Py_VerboseFlag)
  242.                 PySys_WriteStderr("# clear sys.%s\n", *p);
  243.             PyDict_SetItemString(dict, *p, Py_None);
  244.         }
  245.         for (p = sys_files; *p != NULL; p+=2) {
  246.             if (Py_VerboseFlag)
  247.                 PySys_WriteStderr("# restore sys.%s\n", *p);
  248.             v = PyDict_GetItemString(dict, *(p+1));
  249.             if (v == NULL)
  250.                 v = Py_None;
  251.             PyDict_SetItemString(dict, *p, v);
  252.         }
  253.     }
  254.  
  255.     /* First, delete __main__ */
  256.     value = PyDict_GetItemString(modules, "__main__");
  257.     if (value != NULL && PyModule_Check(value)) {
  258.         if (Py_VerboseFlag)
  259.             PySys_WriteStderr("# cleanup __main__\n");
  260.         _PyModule_Clear(value);
  261.         PyDict_SetItemString(modules, "__main__", Py_None);
  262.     }
  263.  
  264.     /* The special treatment of __builtin__ here is because even
  265.        when it's not referenced as a module, its dictionary is
  266.        referenced by almost every module's __builtins__.  Since
  267.        deleting a module clears its dictionary (even if there are
  268.        references left to it), we need to delete the __builtin__
  269.        module last.  Likewise, we don't delete sys until the very
  270.        end because it is implicitly referenced (e.g. by print).
  271.  
  272.        Also note that we 'delete' modules by replacing their entry
  273.        in the modules dict with None, rather than really deleting
  274.        them; this avoids a rehash of the modules dictionary and
  275.        also marks them as "non existent" so they won't be
  276.        re-imported. */
  277.  
  278.     /* Next, repeatedly delete modules with a reference count of
  279.        one (skipping __builtin__ and sys) and delete them */
  280.     do {
  281.         ndone = 0;
  282.         pos = 0;
  283.         while (PyDict_Next(modules, &pos, &key, &value)) {
  284.             if (value->ob_refcnt != 1)
  285.                 continue;
  286.             if (PyString_Check(key) && PyModule_Check(value)) {
  287.                 name = PyString_AS_STRING(key);
  288.                 if (strcmp(name, "__builtin__") == 0)
  289.                     continue;
  290.                 if (strcmp(name, "sys") == 0)
  291.                     continue;
  292.                 if (Py_VerboseFlag)
  293.                     PySys_WriteStderr(
  294.                         "# cleanup[1] %s\n", name);
  295.                 _PyModule_Clear(value);
  296.                 PyDict_SetItem(modules, key, Py_None);
  297.                 ndone++;
  298.             }
  299.         }
  300.     } while (ndone > 0);
  301.  
  302.     /* Next, delete all modules (still skipping __builtin__ and sys) */
  303.     pos = 0;
  304.     while (PyDict_Next(modules, &pos, &key, &value)) {
  305.         if (PyString_Check(key) && PyModule_Check(value)) {
  306.             name = PyString_AS_STRING(key);
  307.             if (strcmp(name, "__builtin__") == 0)
  308.                 continue;
  309.             if (strcmp(name, "sys") == 0)
  310.                 continue;
  311.             if (Py_VerboseFlag)
  312.                 PySys_WriteStderr("# cleanup[2] %s\n", name);
  313.             _PyModule_Clear(value);
  314.             PyDict_SetItem(modules, key, Py_None);
  315.         }
  316.     }
  317.  
  318.     /* Next, delete sys and __builtin__ (in that order) */
  319.     value = PyDict_GetItemString(modules, "sys");
  320.     if (value != NULL && PyModule_Check(value)) {
  321.         if (Py_VerboseFlag)
  322.             PySys_WriteStderr("# cleanup sys\n");
  323.         _PyModule_Clear(value);
  324.         PyDict_SetItemString(modules, "sys", Py_None);
  325.     }
  326.     value = PyDict_GetItemString(modules, "__builtin__");
  327.     if (value != NULL && PyModule_Check(value)) {
  328.         if (Py_VerboseFlag)
  329.             PySys_WriteStderr("# cleanup __builtin__\n");
  330.         _PyModule_Clear(value);
  331.         PyDict_SetItemString(modules, "__builtin__", Py_None);
  332.     }
  333.  
  334.     /* Finally, clear and delete the modules directory */
  335.     PyDict_Clear(modules);
  336.     interp->modules = NULL;
  337.     Py_DECREF(modules);
  338. }
  339.  
  340.  
  341. /* Helper for pythonrun.c -- return magic number */
  342.  
  343. long
  344. PyImport_GetMagicNumber()
  345. {
  346.     return MAGIC;
  347. }
  348.  
  349.  
  350. /* Magic for extension modules (built-in as well as dynamically
  351.    loaded).  To prevent initializing an extension module more than
  352.    once, we keep a static dictionary 'extensions' keyed by module name
  353.    (for built-in modules) or by filename (for dynamically loaded
  354.    modules), containing these modules.  A copy od the module's
  355.    dictionary is stored by calling _PyImport_FixupExtension()
  356.    immediately after the module initialization function succeeds.  A
  357.    copy can be retrieved from there by calling
  358.    _PyImport_FindExtension(). */
  359.  
  360. PyObject *
  361. _PyImport_FixupExtension(name, filename)
  362.     char *name;
  363.     char *filename;
  364. {
  365.     PyObject *modules, *mod, *dict, *copy;
  366.     if (extensions == NULL) {
  367.         extensions = PyDict_New();
  368.         if (extensions == NULL)
  369.             return NULL;
  370.     }
  371.     modules = PyImport_GetModuleDict();
  372.     mod = PyDict_GetItemString(modules, name);
  373.     if (mod == NULL || !PyModule_Check(mod)) {
  374.         PyErr_Format(PyExc_SystemError,
  375.           "_PyImport_FixupExtension: module %.200s not loaded", name);
  376.         return NULL;
  377.     }
  378.     dict = PyModule_GetDict(mod);
  379.     if (dict == NULL)
  380.         return NULL;
  381.     copy = PyObject_CallMethod(dict, "copy", "");
  382.     if (copy == NULL)
  383.         return NULL;
  384.     PyDict_SetItemString(extensions, filename, copy);
  385.     Py_DECREF(copy);
  386.     return copy;
  387. }
  388.  
  389. PyObject *
  390. _PyImport_FindExtension(name, filename)
  391.     char *name;
  392.     char *filename;
  393. {
  394.     PyObject *dict, *mod, *mdict, *result;
  395.     if (extensions == NULL)
  396.         return NULL;
  397.     dict = PyDict_GetItemString(extensions, filename);
  398.     if (dict == NULL)
  399.         return NULL;
  400.     mod = PyImport_AddModule(name);
  401.     if (mod == NULL)
  402.         return NULL;
  403.     mdict = PyModule_GetDict(mod);
  404.     if (mdict == NULL)
  405.         return NULL;
  406.     result = PyObject_CallMethod(mdict, "update", "O", dict);
  407.     if (result == NULL)
  408.         return NULL;
  409.     Py_DECREF(result);
  410.     if (Py_VerboseFlag)
  411.         PySys_WriteStderr("import %s # previously loaded (%s)\n",
  412.             name, filename);
  413.     return mod;
  414. }
  415.  
  416.  
  417. /* Get the module object corresponding to a module name.
  418.    First check the modules dictionary if there's one there,
  419.    if not, create a new one and insert in in the modules dictionary.
  420.    Because the former action is most common, THIS DOES NOT RETURN A
  421.    'NEW' REFERENCE! */
  422.  
  423. PyObject *
  424. PyImport_AddModule(name)
  425.     char *name;
  426. {
  427.     PyObject *modules = PyImport_GetModuleDict();
  428.     PyObject *m;
  429.  
  430.     if ((m = PyDict_GetItemString(modules, name)) != NULL &&
  431.         PyModule_Check(m))
  432.         return m;
  433.     m = PyModule_New(name);
  434.     if (m == NULL)
  435.         return NULL;
  436.     if (PyDict_SetItemString(modules, name, m) != 0) {
  437.         Py_DECREF(m);
  438.         return NULL;
  439.     }
  440.     Py_DECREF(m); /* Yes, it still exists, in modules! */
  441.  
  442.     return m;
  443. }
  444.  
  445.  
  446. /* Execute a code object in a module and return the module object
  447.    WITH INCREMENTED REFERENCE COUNT */
  448.  
  449. PyObject *
  450. PyImport_ExecCodeModule(name, co)
  451.     char *name;
  452.     PyObject *co;
  453. {
  454.     return PyImport_ExecCodeModuleEx(name, co, (char *)NULL);
  455. }
  456.  
  457. PyObject *
  458. PyImport_ExecCodeModuleEx(name, co, pathname)
  459.     char *name;
  460.     PyObject *co;
  461.     char *pathname;
  462. {
  463.     PyObject *modules = PyImport_GetModuleDict();
  464.     PyObject *m, *d, *v;
  465.  
  466.     m = PyImport_AddModule(name);
  467.     if (m == NULL)
  468.         return NULL;
  469.     d = PyModule_GetDict(m);
  470.     if (PyDict_GetItemString(d, "__builtins__") == NULL) {
  471.         if (PyDict_SetItemString(d, "__builtins__",
  472.                      PyEval_GetBuiltins()) != 0)
  473.             return NULL;
  474.     }
  475.     /* Remember the filename as the __file__ attribute */
  476.     v = NULL;
  477.     if (pathname != NULL) {
  478.         v = PyString_FromString(pathname);
  479.         if (v == NULL)
  480.             PyErr_Clear();
  481.     }
  482.     if (v == NULL) {
  483.         v = ((PyCodeObject *)co)->co_filename;
  484.         Py_INCREF(v);
  485.     }
  486.     if (PyDict_SetItemString(d, "__file__", v) != 0)
  487.         PyErr_Clear(); /* Not important enough to report */
  488.     Py_DECREF(v);
  489.  
  490.     v = PyEval_EvalCode((PyCodeObject *)co, d, d);
  491.     if (v == NULL)
  492.         return NULL;
  493.     Py_DECREF(v);
  494.  
  495.     if ((m = PyDict_GetItemString(modules, name)) == NULL) {
  496.         PyErr_Format(PyExc_ImportError,
  497.                  "Loaded module %.200s not found in sys.modules",
  498.                  name);
  499.         return NULL;
  500.     }
  501.  
  502.     Py_INCREF(m);
  503.  
  504.     return m;
  505. }
  506.  
  507.  
  508. /* Given a pathname for a Python source file, fill a buffer with the
  509.    pathname for the corresponding compiled file.  Return the pathname
  510.    for the compiled file, or NULL if there's no space in the buffer.
  511.    Doesn't set an exception. */
  512.  
  513. static char *
  514. make_compiled_pathname(pathname, buf, buflen)
  515.     char *pathname;
  516.     char *buf;
  517.     int buflen;
  518. {
  519.     int len;
  520.  
  521.     len = strlen(pathname);
  522.     if (len+2 > buflen)
  523.         return NULL;
  524.     strcpy(buf, pathname);
  525.     strcpy(buf+len, Py_OptimizeFlag ? "o" : "c");
  526.  
  527.     return buf;
  528. }
  529.  
  530.  
  531. /* Given a pathname for a Python source file, its time of last
  532.    modification, and a pathname for a compiled file, check whether the
  533.    compiled file represents the same version of the source.  If so,
  534.    return a FILE pointer for the compiled file, positioned just after
  535.    the header; if not, return NULL.
  536.    Doesn't set an exception. */
  537.  
  538. static FILE *
  539. check_compiled_module(pathname, mtime, cpathname)
  540.     char *pathname;
  541.     long mtime;
  542.     char *cpathname;
  543. {
  544.     FILE *fp;
  545.     long magic;
  546.     long pyc_mtime;
  547.  
  548.     fp = fopen(cpathname, "rb");
  549.     if (fp == NULL)
  550.         return NULL;
  551.     magic = PyMarshal_ReadLongFromFile(fp);
  552.     if (magic != MAGIC) {
  553.         if (Py_VerboseFlag)
  554.             PySys_WriteStderr("# %s has bad magic\n", cpathname);
  555.         fclose(fp);
  556.         return NULL;
  557.     }
  558.     pyc_mtime = PyMarshal_ReadLongFromFile(fp);
  559.     if (pyc_mtime != mtime) {
  560.         if (Py_VerboseFlag)
  561.             PySys_WriteStderr("# %s has bad mtime\n", cpathname);
  562.         fclose(fp);
  563.         return NULL;
  564.     }
  565.     if (Py_VerboseFlag)
  566.         PySys_WriteStderr("# %s matches %s\n", cpathname, pathname);
  567.     return fp;
  568. }
  569.  
  570.  
  571. /* Read a code object from a file and check it for validity */
  572.  
  573. static PyCodeObject *
  574. read_compiled_module(cpathname, fp)
  575.     char *cpathname;
  576.     FILE *fp;
  577. {
  578.     PyObject *co;
  579.  
  580.     co = PyMarshal_ReadObjectFromFile(fp);
  581.     /* Ugly: rd_object() may return NULL with or without error */
  582.     if (co == NULL || !PyCode_Check(co)) {
  583.         if (!PyErr_Occurred())
  584.             PyErr_Format(PyExc_ImportError,
  585.                 "Non-code object in %.200s", cpathname);
  586.         Py_XDECREF(co);
  587.         return NULL;
  588.     }
  589.     return (PyCodeObject *)co;
  590. }
  591.  
  592.  
  593. /* Load a module from a compiled file, execute it, and return its
  594.    module object WITH INCREMENTED REFERENCE COUNT */
  595.  
  596. static PyObject *
  597. load_compiled_module(name, cpathname, fp)
  598.     char *name;
  599.     char *cpathname;
  600.     FILE *fp;
  601. {
  602.     long magic;
  603.     PyCodeObject *co;
  604.     PyObject *m;
  605.  
  606.     magic = PyMarshal_ReadLongFromFile(fp);
  607.     if (magic != MAGIC) {
  608.         PyErr_Format(PyExc_ImportError,
  609.                  "Bad magic number in %.200s", cpathname);
  610.         return NULL;
  611.     }
  612.     (void) PyMarshal_ReadLongFromFile(fp);
  613.     co = read_compiled_module(cpathname, fp);
  614.     if (co == NULL)
  615.         return NULL;
  616.     if (Py_VerboseFlag)
  617.         PySys_WriteStderr("import %s # precompiled from %s\n",
  618.             name, cpathname);
  619.     m = PyImport_ExecCodeModuleEx(name, (PyObject *)co, cpathname);
  620.     Py_DECREF(co);
  621.  
  622.     return m;
  623. }
  624.  
  625. /* Parse a source file and return the corresponding code object */
  626.  
  627. static PyCodeObject *
  628. parse_source_module(pathname, fp)
  629.     char *pathname;
  630.     FILE *fp;
  631. {
  632.     PyCodeObject *co;
  633.     node *n;
  634.  
  635.     n = PyParser_SimpleParseFile(fp, pathname, Py_file_input);
  636.     if (n == NULL)
  637.         return NULL;
  638.     co = PyNode_Compile(n, pathname);
  639.     PyNode_Free(n);
  640.  
  641.     return co;
  642. }
  643.  
  644.  
  645. /* Write a compiled module to a file, placing the time of last
  646.    modification of its source into the header.
  647.    Errors are ignored, if a write error occurs an attempt is made to
  648.    remove the file. */
  649.  
  650. static void
  651. write_compiled_module(co, cpathname, mtime)
  652.     PyCodeObject *co;
  653.     char *cpathname;
  654.     long mtime;
  655. {
  656.     FILE *fp;
  657.  
  658.     fp = fopen(cpathname, "wb");
  659.     if (fp == NULL) {
  660.         if (Py_VerboseFlag)
  661.             PySys_WriteStderr(
  662.                 "# can't create %s\n", cpathname);
  663.         return;
  664.     }
  665.     PyMarshal_WriteLongToFile(MAGIC, fp);
  666.     /* First write a 0 for mtime */
  667.     PyMarshal_WriteLongToFile(0L, fp);
  668.     PyMarshal_WriteObjectToFile((PyObject *)co, fp);
  669.     if (ferror(fp)) {
  670.         if (Py_VerboseFlag)
  671.             PySys_WriteStderr("# can't write %s\n", cpathname);
  672.         /* Don't keep partial file */
  673.         fclose(fp);
  674.         (void) unlink(cpathname);
  675.         return;
  676.     }
  677.     /* Now write the true mtime */
  678.     fseek(fp, 4L, 0);
  679.     PyMarshal_WriteLongToFile(mtime, fp);
  680.     fflush(fp);
  681.     fclose(fp);
  682.     if (Py_VerboseFlag)
  683.         PySys_WriteStderr("# wrote %s\n", cpathname);
  684. #ifdef macintosh
  685.     setfiletype(cpathname, 'Pyth', 'PYC ');
  686. #endif
  687. }
  688.  
  689.  
  690. /* Load a source module from a given file and return its module
  691.    object WITH INCREMENTED REFERENCE COUNT.  If there's a matching
  692.    byte-compiled file, use that instead. */
  693.  
  694. static PyObject *
  695. load_source_module(name, pathname, fp)
  696.     char *name;
  697.     char *pathname;
  698.     FILE *fp;
  699. {
  700.     long mtime;
  701.     FILE *fpc;
  702.     char buf[MAXPATHLEN+1];
  703.     char *cpathname;
  704.     PyCodeObject *co;
  705.     PyObject *m;
  706.  
  707.     mtime = PyOS_GetLastModificationTime(pathname, fp);
  708.     cpathname = make_compiled_pathname(pathname, buf, MAXPATHLEN+1);
  709.     if (cpathname != NULL &&
  710.         (fpc = check_compiled_module(pathname, mtime, cpathname))) {
  711.         co = read_compiled_module(cpathname, fpc);
  712.         fclose(fpc);
  713.         if (co == NULL)
  714.             return NULL;
  715.         if (Py_VerboseFlag)
  716.             PySys_WriteStderr("import %s # precompiled from %s\n",
  717.                 name, cpathname);
  718.         pathname = cpathname;
  719.     }
  720.     else {
  721.         co = parse_source_module(pathname, fp);
  722.         if (co == NULL)
  723.             return NULL;
  724.         if (Py_VerboseFlag)
  725.             PySys_WriteStderr("import %s # from %s\n",
  726.                 name, pathname);
  727.         write_compiled_module(co, cpathname, mtime);
  728.     }
  729.     m = PyImport_ExecCodeModuleEx(name, (PyObject *)co, pathname);
  730.     Py_DECREF(co);
  731.  
  732.     return m;
  733. }
  734.  
  735.  
  736. /* Forward */
  737. static PyObject *load_module Py_PROTO((char *, FILE *, char *, int));
  738. static struct filedescr *find_module Py_PROTO((char *, PyObject *,
  739.                            char *, int, FILE **));
  740. static struct _frozen *find_frozen Py_PROTO((char *name));
  741.  
  742. /* Load a package and return its module object WITH INCREMENTED
  743.    REFERENCE COUNT */
  744.  
  745. static PyObject *
  746. load_package(name, pathname)
  747.     char *name;
  748.     char *pathname;
  749. {
  750.     PyObject *m, *d, *file, *path;
  751.     int err;
  752.     char buf[MAXPATHLEN+1];
  753.     FILE *fp = NULL;
  754.     struct filedescr *fdp;
  755.  
  756.     m = PyImport_AddModule(name);
  757.     if (m == NULL)
  758.         return NULL;
  759.     if (Py_VerboseFlag)
  760.         PySys_WriteStderr("import %s # directory %s\n",
  761.             name, pathname);
  762.     d = PyModule_GetDict(m);
  763.     file = PyString_FromString(pathname);
  764.     if (file == NULL)
  765.         return NULL;
  766.     path = Py_BuildValue("[O]", file);
  767.     if (path == NULL) {
  768.         Py_DECREF(file);
  769.         return NULL;
  770.     }
  771.     err = PyDict_SetItemString(d, "__file__", file);
  772.     if (err == 0)
  773.         err = PyDict_SetItemString(d, "__path__", path);
  774.     if (err != 0) {
  775.         m = NULL;
  776.         goto cleanup;
  777.     }
  778.     buf[0] = '\0';
  779.     fdp = find_module("__init__", path, buf, sizeof(buf), &fp);
  780.     if (fdp == NULL) {
  781.         if (PyErr_ExceptionMatches(PyExc_ImportError)) {
  782.             PyErr_Clear();
  783.         }
  784.         else
  785.             m = NULL;
  786.         goto cleanup;
  787.     }
  788.     m = load_module(name, fp, buf, fdp->type);
  789.     if (fp != NULL)
  790.         fclose(fp);
  791.   cleanup:
  792.     Py_XDECREF(path);
  793.     Py_XDECREF(file);
  794.     return m;
  795. }
  796.  
  797.  
  798. /* Helper to test for built-in module */
  799.  
  800. static int
  801. is_builtin(name)
  802.     char *name;
  803. {
  804.     int i;
  805.     for (i = 0; PyImport_Inittab[i].name != NULL; i++) {
  806.         if (strcmp(name, PyImport_Inittab[i].name) == 0) {
  807.             if (PyImport_Inittab[i].initfunc == NULL)
  808.                 return -1;
  809.             else
  810.                 return 1;
  811.         }
  812.     }
  813.     return 0;
  814. }
  815.  
  816.  
  817. /* Search the path (default sys.path) for a module.  Return the
  818.    corresponding filedescr struct, and (via return arguments) the
  819.    pathname and an open file.  Return NULL if the module is not found. */
  820.  
  821. #ifdef MS_COREDLL
  822. extern FILE *PyWin_FindRegisteredModule();
  823. #endif
  824.  
  825. #ifdef CHECK_IMPORT_CASE
  826. static int check_case(char *, int, int, char *);
  827. #endif
  828.  
  829. static int find_init_module Py_PROTO((char *)); /* Forward */
  830.  
  831. static struct filedescr *
  832. find_module(realname, path, buf, buflen, p_fp)
  833.     char *realname;
  834.     PyObject *path;
  835.     /* Output parameters: */
  836.     char *buf;
  837.     int buflen;
  838.     FILE **p_fp;
  839. {
  840.     int i, npath, len, namelen;
  841.     struct _frozen *f;
  842.     struct filedescr *fdp = NULL;
  843.     FILE *fp = NULL;
  844.     struct stat statbuf;
  845.     static struct filedescr fd_frozen = {"", "", PY_FROZEN};
  846.     static struct filedescr fd_builtin = {"", "", C_BUILTIN};
  847.     static struct filedescr fd_package = {"", "", PKG_DIRECTORY};
  848.     char name[MAXPATHLEN+1];
  849.  
  850.     strcpy(name, realname);
  851.  
  852.     if (path != NULL && PyString_Check(path)) {
  853.         /* Submodule of "frozen" package:
  854.            Set name to the fullname, path to NULL
  855.            and continue as "usual" */
  856.         if (PyString_Size(path) + 1 + strlen(name) >= (size_t)buflen) {
  857.             PyErr_SetString(PyExc_ImportError,
  858.                     "full frozen module name too long");
  859.             return NULL;
  860.         }
  861.         strcpy(buf, PyString_AsString(path));
  862.         strcat(buf, ".");
  863.         strcat(buf, name);
  864.         strcpy(name, buf);
  865.         path = NULL;
  866.     }
  867.     if (path == NULL) {
  868.         if (is_builtin(name)) {
  869.             strcpy(buf, name);
  870.             return &fd_builtin;
  871.         }
  872.         if ((f = find_frozen(name)) != NULL) {
  873.             strcpy(buf, name);
  874.             return &fd_frozen;
  875.         }
  876.  
  877. #ifdef MS_COREDLL
  878.         fp = PyWin_FindRegisteredModule(name, &fdp, buf, buflen);
  879.         if (fp != NULL) {
  880.             *p_fp = fp;
  881.             return fdp;
  882.         }
  883. #endif
  884.         path = PySys_GetObject("path");
  885.     }
  886.     if (path == NULL || !PyList_Check(path)) {
  887.         PyErr_SetString(PyExc_ImportError,
  888.                 "sys.path must be a list of directory names");
  889.         return NULL;
  890.     }
  891.     npath = PyList_Size(path);
  892.     namelen = strlen(name);
  893.     for (i = 0; i < npath; i++) {
  894.         PyObject *v = PyList_GetItem(path, i);
  895.         if (!PyString_Check(v))
  896.             continue;
  897.         len = PyString_Size(v);
  898.         if (len + 2 + namelen + MAXSUFFIXSIZE >= buflen)
  899.             continue; /* Too long */
  900.         strcpy(buf, PyString_AsString(v));
  901.         if ((int)strlen(buf) != len)
  902.             continue; /* v contains '\0' */
  903. #ifdef macintosh
  904. #ifdef INTERN_STRINGS
  905.         /* 
  906.         ** Speedup: each sys.path item is interned, and
  907.         ** FindResourceModule remembers which items refer to
  908.         ** folders (so we don't have to bother trying to look
  909.         ** into them for resources). 
  910.         */
  911.         PyString_InternInPlace(&PyList_GET_ITEM(path, i));
  912.         v = PyList_GET_ITEM(path, i);
  913. #endif
  914.         if (PyMac_FindResourceModule((PyStringObject *)v, name, buf)) {
  915.             static struct filedescr resfiledescr =
  916.                 {"", "", PY_RESOURCE};
  917.             
  918.             return &resfiledescr;
  919.         }
  920.         if (PyMac_FindCodeResourceModule((PyStringObject *)v, name, buf)) {
  921.             static struct filedescr resfiledescr =
  922.                 {"", "", PY_CODERESOURCE};
  923.             
  924.             return &resfiledescr;
  925.         }
  926. #endif
  927. #ifdef _AMIGA
  928.         /* Use the dos.library to construct the pathname */
  929.         AddPart(buf,name,MAXPATHLEN);
  930.         len=strlen(buf);
  931. #else /* !_AMIGA */
  932.         if (len > 0 && buf[len-1] != SEP
  933. #ifdef ALTSEP
  934.             && buf[len-1] != ALTSEP
  935. #endif
  936.             )
  937.             buf[len++] = SEP;
  938. #ifdef IMPORT_8x3_NAMES
  939.         /* see if we are searching in directory dos-8x3 */
  940.         if (len > 7 && !strncmp(buf + len - 8, "dos-8x3", 7)){
  941.             int j;
  942.             char ch;  /* limit name to 8 lower-case characters */
  943.             for (j = 0; (ch = name[j]) && j < 8; j++)
  944.                 if (isupper(ch))
  945.                     buf[len++] = tolower(ch);
  946.                 else
  947.                     buf[len++] = ch;
  948.         }
  949.         else /* Not in dos-8x3, use the full name */
  950. #endif
  951.         {
  952.             strcpy(buf+len, name);
  953.             len += namelen;
  954.         }
  955. #endif /* !_AMIGA */
  956. #ifdef HAVE_STAT
  957.         if (stat(buf, &statbuf) == 0) {
  958.             if (S_ISDIR(statbuf.st_mode)) {
  959.                 if (find_init_module(buf)) {
  960. #ifdef CHECK_IMPORT_CASE
  961.                     if (!check_case(buf, len, namelen,
  962.                             name))
  963.                         return NULL;
  964. #endif
  965.                     return &fd_package;
  966.                 }
  967.             }
  968.         }
  969. #else
  970.         /* XXX How are you going to test for directories? */
  971. #endif
  972. #ifdef macintosh
  973.         fdp = PyMac_FindModuleExtension(buf, &len, name);
  974.         if (fdp)
  975.             fp = fopen(buf, fdp->mode);
  976. #else
  977.         for (fdp = _PyImport_Filetab; fdp->suffix != NULL; fdp++) {
  978.             strcpy(buf+len, fdp->suffix);
  979.             if (Py_VerboseFlag > 1)
  980.                 PySys_WriteStderr("# trying %s\n", buf);
  981.             fp = fopen(buf, fdp->mode);
  982.             if (fp != NULL)
  983.                 break;
  984.         }
  985. #endif /* !macintosh */
  986.         if (fp != NULL)
  987.             break;
  988.     }
  989.     if (fp == NULL) {
  990.         PyErr_Format(PyExc_ImportError,
  991.                  "No module named %.200s", name);
  992.         return NULL;
  993.     }
  994. #ifdef CHECK_IMPORT_CASE
  995.     if (!check_case(buf, len, namelen, name)) {
  996.         fclose(fp);
  997.         return NULL;
  998.     }
  999. #endif
  1000.  
  1001.     *p_fp = fp;
  1002.     return fdp;
  1003. }
  1004.  
  1005. #ifdef CHECK_IMPORT_CASE
  1006.  
  1007. #ifdef MS_WIN32
  1008. #include <windows.h>
  1009. #include <ctype.h>
  1010.  
  1011. static int
  1012. allcaps8x3(s)
  1013.     char *s;
  1014. {
  1015.     /* Return 1 if s is an 8.3 filename in ALLCAPS */
  1016.     char c;
  1017.     char *dot = strchr(s, '.');
  1018.     char *end = strchr(s, '\0');
  1019.     if (dot != NULL) {
  1020.         if (dot-s > 8)
  1021.             return 1; /* More than 8 before '.' */
  1022.         if (end-dot > 4)
  1023.             return 1; /* More than 3 after '.' */
  1024.         end = strchr(dot+1, '.');
  1025.         if (end != NULL)
  1026.             return 1; /* More than one dot  */
  1027.     }
  1028.     else if (end-s > 8)
  1029.         return 1; /* More than 8 and no dot */
  1030.     while ((c = *s++)) {
  1031.         if (islower(c))
  1032.             return 0;
  1033.     }
  1034.     return 1;
  1035. }
  1036.  
  1037. static int
  1038. check_case(char *buf, int len, int namelen, char *name)
  1039. {
  1040.     WIN32_FIND_DATA data;
  1041.     HANDLE h;
  1042.     if (getenv("PYTHONCASEOK") != NULL)
  1043.         return 1;
  1044.     h = FindFirstFile(buf, &data);
  1045.     if (h == INVALID_HANDLE_VALUE) {
  1046.         PyErr_Format(PyExc_NameError,
  1047.           "Can't find file for module %.100s\n(filename %.300s)",
  1048.           name, buf);
  1049.         return 0;
  1050.     }
  1051.     FindClose(h);
  1052.     if (allcaps8x3(data.cFileName)) {
  1053.         /* Skip the test if the filename is ALL.CAPS.  This can
  1054.            happen in certain circumstances beyond our control,
  1055.            e.g. when software is installed under NT on a FAT
  1056.            filesystem and then the same FAT filesystem is used
  1057.            under Windows 95. */
  1058.         return 1;
  1059.     }
  1060.     if (strncmp(data.cFileName, name, namelen) != 0) {
  1061.         strcpy(buf+len-namelen, data.cFileName);
  1062.         PyErr_Format(PyExc_NameError,
  1063.           "Case mismatch for module name %.100s\n(filename %.300s)",
  1064.           name, buf);
  1065.         return 0;
  1066.     }
  1067.     return 1;
  1068. }
  1069. #endif /* MS_WIN32 */
  1070.  
  1071. #ifdef macintosh
  1072. #include <TextUtils.h>
  1073. #ifdef USE_GUSI
  1074. #include "TFileSpec.h"        /* for Path2FSSpec() */
  1075. #endif
  1076. static int
  1077. check_case(char *buf, int len, int namelen, char *name)
  1078. {
  1079.     FSSpec fss;
  1080.     OSErr err;
  1081. #ifndef USE_GUSI
  1082.     err = FSMakeFSSpec(0, 0, Pstring(buf), &fss);
  1083. #else
  1084.     /* GUSI's Path2FSSpec() resolves all possible aliases nicely on
  1085.        the way, which is fine for all directories, but here we need
  1086.        the original name of the alias file (say, Dlg.ppc.slb, not
  1087.        toolboxmodules.ppc.slb). */
  1088.     char *colon;
  1089.     err = Path2FSSpec(buf, &fss);
  1090.     if (err == noErr) {
  1091.         colon = strrchr(buf, ':'); /* find filename */
  1092.         if (colon != NULL)
  1093.             err = FSMakeFSSpec(fss.vRefNum, fss.parID,
  1094.                        Pstring(colon+1), &fss);
  1095.         else
  1096.             err = FSMakeFSSpec(fss.vRefNum, fss.parID,
  1097.                        fss.name, &fss);
  1098.     }
  1099. #endif
  1100.     if (err) {
  1101.         PyErr_Format(PyExc_NameError,
  1102.              "Can't find file for module %.100s\n(filename %.300s)",
  1103.              name, buf);
  1104.         return 0;
  1105.     }
  1106.     p2cstr(fss.name);
  1107.     if ( strncmp(name, (char *)fss.name, namelen) != 0 ) {
  1108.         PyErr_Format(PyExc_NameError,
  1109.              "Case mismatch for module name %.100s\n(filename %.300s)",
  1110.              name, fss.name);
  1111.         return 0;
  1112.     }
  1113.     return 1;
  1114. }
  1115. #endif /* macintosh */
  1116.  
  1117. #ifdef DJGPP
  1118. #include <dir.h>
  1119.  
  1120. static int
  1121. check_case(char *buf, int len, int namelen, char *name)
  1122. {
  1123.     struct ffblk ffblk;
  1124.     int done;
  1125.  
  1126.     if (getenv("PYTHONCASEOK") != NULL)
  1127.         return 1;
  1128.     done = findfirst(buf, &ffblk, FA_ARCH|FA_RDONLY|FA_HIDDEN|FA_DIREC);
  1129.     if (done) {
  1130.         PyErr_Format(PyExc_NameError,
  1131.           "Can't find file for module %.100s\n(filename %.300s)",
  1132.           name, buf);
  1133.         return 0;
  1134.     }
  1135.  
  1136.     if (strncmp(ffblk.ff_name, name, namelen) != 0) {
  1137.         strcpy(buf+len-namelen, ffblk.ff_name);
  1138.         PyErr_Format(PyExc_NameError,
  1139.           "Case mismatch for module name %.100s\n(filename %.300s)",
  1140.           name, buf);
  1141.         return 0;
  1142.     }
  1143.     return 1;
  1144. }
  1145. #endif
  1146.  
  1147. #ifdef _AMIGA
  1148. static int
  1149. check_case(char *buf, int len, int namelen, char *name)
  1150. {
  1151.     BPTR lock;
  1152.     struct FileInfoBlock __aligned fib;
  1153.     char tmpbuf[200];
  1154.  
  1155.     if(GetVar("PYTHONCASEOK",tmpbuf,200,NULL)>=0)
  1156.         return 1;
  1157.  
  1158.     if(lock=Lock(buf,ACCESS_READ))
  1159.     {
  1160.         if(Examine(lock,&fib))
  1161.         {
  1162.             UnLock(lock);
  1163.             if (strncmp(fib.fib_FileName, name, namelen) != 0)
  1164.             {
  1165.                 strcpy(buf+len-namelen, fib.fib_FileName);
  1166.                 PyErr_Format(PyExc_NameError,
  1167.                   "Case mismatch for module name %.100s\n(filename %.300s)",
  1168.                   name, buf);
  1169.                 return 0;
  1170.             }
  1171.             return 1;
  1172.         }
  1173.         UnLock(lock);
  1174.     }
  1175.     PyErr_Format(PyExc_NameError,
  1176.       "Can't find file for module %.100s\n(filename %.300s)",
  1177.       name, buf);
  1178.     return 0;
  1179. }
  1180. #endif /* _AMIGA */
  1181.  
  1182. #endif /* CHECK_IMPORT_CASE */
  1183.  
  1184. #ifdef HAVE_STAT
  1185. /* Helper to look for __init__.py or __init__.py[co] in potential package */
  1186. static int
  1187. find_init_module(buf)
  1188.     char *buf;
  1189. {
  1190.     int save_len = strlen(buf);
  1191.     int i = save_len;
  1192.     struct stat statbuf;
  1193.  
  1194.     if (save_len + 13 >= MAXPATHLEN)
  1195.         return 0;
  1196.     buf[i++] = SEP;
  1197.     strcpy(buf+i, "__init__.py");
  1198.     if (stat(buf, &statbuf) == 0) {
  1199.         buf[save_len] = '\0';
  1200.         return 1;
  1201.     }
  1202.     i += strlen(buf+i);
  1203.     if (Py_OptimizeFlag)
  1204.         strcpy(buf+i, "o");
  1205.     else
  1206.         strcpy(buf+i, "c");
  1207.     if (stat(buf, &statbuf) == 0) {
  1208.         buf[save_len] = '\0';
  1209.         return 1;
  1210.     }
  1211.     buf[save_len] = '\0';
  1212.     return 0;
  1213. }
  1214. #endif /* HAVE_STAT */
  1215.  
  1216.  
  1217. static int init_builtin Py_PROTO((char *)); /* Forward */
  1218.  
  1219. /* Load an external module using the default search path and return
  1220.    its module object WITH INCREMENTED REFERENCE COUNT */
  1221.  
  1222. static PyObject *
  1223. load_module(name, fp, buf, type)
  1224.     char *name;
  1225.     FILE *fp;
  1226.     char *buf;
  1227.     int type;
  1228. {
  1229.     PyObject *modules;
  1230.     PyObject *m;
  1231.     int err;
  1232.  
  1233.     /* First check that there's an open file (if we need one)  */
  1234.     switch (type) {
  1235.     case PY_SOURCE:
  1236.     case PY_COMPILED:
  1237.         if (fp == NULL) {
  1238.             PyErr_Format(PyExc_ValueError,
  1239.                "file object required for import (type code %d)",
  1240.                      type);
  1241.             return NULL;
  1242.         }
  1243.     }
  1244.  
  1245.     switch (type) {
  1246.  
  1247.     case PY_SOURCE:
  1248.         m = load_source_module(name, buf, fp);
  1249.         break;
  1250.  
  1251.     case PY_COMPILED:
  1252.         m = load_compiled_module(name, buf, fp);
  1253.         break;
  1254.  
  1255.     case C_EXTENSION:
  1256.         m = _PyImport_LoadDynamicModule(name, buf, fp);
  1257.         break;
  1258.  
  1259. #ifdef macintosh
  1260.     case PY_RESOURCE:
  1261.         m = PyMac_LoadResourceModule(name, buf);
  1262.         break;
  1263.     case PY_CODERESOURCE:
  1264.         m = PyMac_LoadCodeResourceModule(name, buf);
  1265.         break;
  1266. #endif
  1267.  
  1268.     case PKG_DIRECTORY:
  1269.         m = load_package(name, buf);
  1270.         break;
  1271.  
  1272.     case C_BUILTIN:
  1273.     case PY_FROZEN:
  1274.         if (buf != NULL && buf[0] != '\0')
  1275.             name = buf;
  1276.         if (type == C_BUILTIN)
  1277.             err = init_builtin(name);
  1278.         else
  1279.             err = PyImport_ImportFrozenModule(name);
  1280.         if (err < 0)
  1281.             return NULL;
  1282.         if (err == 0) {
  1283.             PyErr_Format(PyExc_ImportError,
  1284.                      "Purported %s module %.200s not found",
  1285.                      type == C_BUILTIN ?
  1286.                         "builtin" : "frozen",
  1287.                      name);
  1288.             return NULL;
  1289.         }
  1290.         modules = PyImport_GetModuleDict();
  1291.         m = PyDict_GetItemString(modules, name);
  1292.         if (m == NULL) {
  1293.             PyErr_Format(
  1294.                 PyExc_ImportError,
  1295.                 "%s module %.200s not properly initialized",
  1296.                 type == C_BUILTIN ?
  1297.                     "builtin" : "frozen",
  1298.                 name);
  1299.             return NULL;
  1300.         }
  1301.         Py_INCREF(m);
  1302.         break;
  1303.  
  1304.     default:
  1305.         PyErr_Format(PyExc_ImportError,
  1306.                  "Don't know how to import %.200s (type code %d)",
  1307.                   name, type);
  1308.         m = NULL;
  1309.  
  1310.     }
  1311.  
  1312.     return m;
  1313. }
  1314.  
  1315.  
  1316. /* Initialize a built-in module.
  1317.    Return 1 for succes, 0 if the module is not found, and -1 with
  1318.    an exception set if the initialization failed. */
  1319.  
  1320. static int
  1321. init_builtin(name)
  1322.     char *name;
  1323. {
  1324.     struct _inittab *p;
  1325.     PyObject *mod;
  1326.  
  1327.     if ((mod = _PyImport_FindExtension(name, name)) != NULL)
  1328.         return 1;
  1329.  
  1330.     for (p = PyImport_Inittab; p->name != NULL; p++) {
  1331.         if (strcmp(name, p->name) == 0) {
  1332.             if (p->initfunc == NULL) {
  1333.                 PyErr_Format(PyExc_ImportError,
  1334.                     "Cannot re-init internal module %.200s",
  1335.                     name);
  1336.                 return -1;
  1337.             }
  1338.             if (Py_VerboseFlag)
  1339.                 PySys_WriteStderr("import %s # builtin\n", name);
  1340.             (*p->initfunc)();
  1341.             if (PyErr_Occurred())
  1342.                 return -1;
  1343.             if (_PyImport_FixupExtension(name, name) == NULL)
  1344.                 return -1;
  1345.             return 1;
  1346.         }
  1347.     }
  1348.     return 0;
  1349. }
  1350.  
  1351.  
  1352. /* Frozen modules */
  1353.  
  1354. static struct _frozen *
  1355. find_frozen(name)
  1356.     char *name;
  1357. {
  1358.     struct _frozen *p;
  1359.  
  1360.     for (p = PyImport_FrozenModules; ; p++) {
  1361.         if (p->name == NULL)
  1362.             return NULL;
  1363.         if (strcmp(p->name, name) == 0)
  1364.             break;
  1365.     }
  1366.     return p;
  1367. }
  1368.  
  1369. static PyObject *
  1370. get_frozen_object(name)
  1371.     char *name;
  1372. {
  1373.     struct _frozen *p = find_frozen(name);
  1374.     int size;
  1375.  
  1376.     if (p == NULL) {
  1377.         PyErr_Format(PyExc_ImportError,
  1378.                  "No such frozen object named %.200s",
  1379.                  name);
  1380.         return NULL;
  1381.     }
  1382.     size = p->size;
  1383.     if (size < 0)
  1384.         size = -size;
  1385.     return PyMarshal_ReadObjectFromString((char *)p->code, size);
  1386. }
  1387.  
  1388. /* Initialize a frozen module.
  1389.    Return 1 for succes, 0 if the module is not found, and -1 with
  1390.    an exception set if the initialization failed.
  1391.    This function is also used from frozenmain.c */
  1392.  
  1393. int
  1394. PyImport_ImportFrozenModule(name)
  1395.     char *name;
  1396. {
  1397.     struct _frozen *p = find_frozen(name);
  1398.     PyObject *co;
  1399.     PyObject *m;
  1400.     int ispackage;
  1401.     int size;
  1402.  
  1403.     if (p == NULL)
  1404.         return 0;
  1405.     size = p->size;
  1406.     ispackage = (size < 0);
  1407.     if (ispackage)
  1408.         size = -size;
  1409.     if (Py_VerboseFlag)
  1410.         PySys_WriteStderr("import %s # frozen%s\n",
  1411.             name, ispackage ? " package" : "");
  1412.     co = PyMarshal_ReadObjectFromString((char *)p->code, size);
  1413.     if (co == NULL)
  1414.         return -1;
  1415.     if (!PyCode_Check(co)) {
  1416.         Py_DECREF(co);
  1417.         PyErr_Format(PyExc_TypeError,
  1418.                  "frozen object %.200s is not a code object",
  1419.                  name);
  1420.         return -1;
  1421.     }
  1422.     if (ispackage) {
  1423.         /* Set __path__ to the package name */
  1424.         PyObject *d, *s;
  1425.         int err;
  1426.         m = PyImport_AddModule(name);
  1427.         if (m == NULL)
  1428.             return -1;
  1429.         d = PyModule_GetDict(m);
  1430.         s = PyString_InternFromString(name);
  1431.         if (s == NULL)
  1432.             return -1;
  1433.         err = PyDict_SetItemString(d, "__path__", s);
  1434.         Py_DECREF(s);
  1435.         if (err != 0)
  1436.             return err;
  1437.     }
  1438.     m = PyImport_ExecCodeModuleEx(name, co, "<frozen>");
  1439.     Py_DECREF(co);
  1440.     if (m == NULL)
  1441.         return -1;
  1442.     Py_DECREF(m);
  1443.     return 1;
  1444. }
  1445.  
  1446.  
  1447. /* Import a module, either built-in, frozen, or external, and return
  1448.    its module object WITH INCREMENTED REFERENCE COUNT */
  1449.  
  1450. PyObject *
  1451. PyImport_ImportModule(name)
  1452.     char *name;
  1453. {
  1454.     static PyObject *fromlist = NULL;
  1455.     if (fromlist == NULL && strchr(name, '.') != NULL) {
  1456.         fromlist = Py_BuildValue("[s]", "*");
  1457.         if (fromlist == NULL)
  1458.             return NULL;
  1459.     }
  1460.     return PyImport_ImportModuleEx(name, NULL, NULL, fromlist);
  1461. }
  1462.  
  1463. /* Forward declarations for helper routines */
  1464. static PyObject *get_parent Py_PROTO((PyObject *globals,
  1465.                       char *buf, int *p_buflen));
  1466. static PyObject *load_next Py_PROTO((PyObject *mod, PyObject *altmod,
  1467.                      char **p_name, char *buf, int *p_buflen));
  1468. static int mark_miss Py_PROTO((char *name));
  1469. static int ensure_fromlist Py_PROTO((PyObject *mod, PyObject *fromlist,
  1470.                      char *buf, int buflen, int recursive));
  1471. static PyObject * import_submodule Py_PROTO((PyObject *mod,
  1472.                          char *name, char *fullname));
  1473.  
  1474. /* The Magnum Opus of dotted-name import :-) */
  1475.  
  1476. static PyObject *
  1477. import_module_ex(name, globals, locals, fromlist)
  1478.     char *name;
  1479.     PyObject *globals;
  1480.     PyObject *locals;
  1481.     PyObject *fromlist;
  1482. {
  1483.     char buf[MAXPATHLEN+1];
  1484.     int buflen = 0;
  1485.     PyObject *parent, *head, *next, *tail;
  1486.  
  1487.     parent = get_parent(globals, buf, &buflen);
  1488.     if (parent == NULL)
  1489.         return NULL;
  1490.  
  1491.     head = load_next(parent, Py_None, &name, buf, &buflen);
  1492.     if (head == NULL)
  1493.         return NULL;
  1494.  
  1495.     tail = head;
  1496.     Py_INCREF(tail);
  1497.     while (name) {
  1498.         next = load_next(tail, tail, &name, buf, &buflen);
  1499.         Py_DECREF(tail);
  1500.         if (next == NULL) {
  1501.             Py_DECREF(head);
  1502.             return NULL;
  1503.         }
  1504.         tail = next;
  1505.     }
  1506.  
  1507.     if (fromlist != NULL) {
  1508.         if (fromlist == Py_None || !PyObject_IsTrue(fromlist))
  1509.             fromlist = NULL;
  1510.     }
  1511.  
  1512.     if (fromlist == NULL) {
  1513.         Py_DECREF(tail);
  1514.         return head;
  1515.     }
  1516.  
  1517.     Py_DECREF(head);
  1518.     if (!ensure_fromlist(tail, fromlist, buf, buflen, 0)) {
  1519.         Py_DECREF(tail);
  1520.         return NULL;
  1521.     }
  1522.  
  1523.     return tail;
  1524. }
  1525.  
  1526. PyObject *
  1527. PyImport_ImportModuleEx(name, globals, locals, fromlist)
  1528.     char *name;
  1529.     PyObject *globals;
  1530.     PyObject *locals;
  1531.     PyObject *fromlist;
  1532. {
  1533.     PyObject *result;
  1534.     lock_import();
  1535.     result = import_module_ex(name, globals, locals, fromlist);
  1536.     unlock_import();
  1537.     return result;
  1538. }
  1539.  
  1540. static PyObject *
  1541. get_parent(globals, buf, p_buflen)
  1542.     PyObject *globals;
  1543.     char *buf;
  1544.     int *p_buflen;
  1545. {
  1546.     static PyObject *namestr = NULL;
  1547.     static PyObject *pathstr = NULL;
  1548.     PyObject *modname, *modpath, *modules, *parent;
  1549.  
  1550.     if (globals == NULL || !PyDict_Check(globals))
  1551.         return Py_None;
  1552.  
  1553.     if (namestr == NULL) {
  1554.         namestr = PyString_InternFromString("__name__");
  1555.         if (namestr == NULL)
  1556.             return NULL;
  1557.     }
  1558.     if (pathstr == NULL) {
  1559.         pathstr = PyString_InternFromString("__path__");
  1560.         if (pathstr == NULL)
  1561.             return NULL;
  1562.     }
  1563.  
  1564.     *buf = '\0';
  1565.     *p_buflen = 0;
  1566.     modname = PyDict_GetItem(globals, namestr);
  1567.     if (modname == NULL || !PyString_Check(modname))
  1568.         return Py_None;
  1569.  
  1570.     modpath = PyDict_GetItem(globals, pathstr);
  1571.     if (modpath != NULL) {
  1572.         int len = PyString_GET_SIZE(modname);
  1573.         if (len > MAXPATHLEN) {
  1574.             PyErr_SetString(PyExc_ValueError,
  1575.                     "Module name too long");
  1576.             return NULL;
  1577.         }
  1578.         strcpy(buf, PyString_AS_STRING(modname));
  1579.         *p_buflen = len;
  1580.     }
  1581.     else {
  1582.         char *start = PyString_AS_STRING(modname);
  1583.         char *lastdot = strrchr(start, '.');
  1584.         int len;
  1585.         if (lastdot == NULL)
  1586.             return Py_None;
  1587.         len = lastdot - start;
  1588.         if (len >= MAXPATHLEN) {
  1589.             PyErr_SetString(PyExc_ValueError,
  1590.                     "Module name too long");
  1591.             return NULL;
  1592.         }
  1593.         strncpy(buf, start, len);
  1594.         buf[len] = '\0';
  1595.         *p_buflen = len;
  1596.     }
  1597.  
  1598.     modules = PyImport_GetModuleDict();
  1599.     parent = PyDict_GetItemString(modules, buf);
  1600.     if (parent == NULL)
  1601.         parent = Py_None;
  1602.     return parent;
  1603.     /* We expect, but can't guarantee, if parent != None, that:
  1604.        - parent.__name__ == buf
  1605.        - parent.__dict__ is globals
  1606.        If this is violated...  Who cares? */
  1607. }
  1608.  
  1609. static PyObject *
  1610. load_next(mod, altmod, p_name, buf, p_buflen)
  1611.     PyObject *mod;
  1612.     PyObject *altmod; /* Either None or same as mod */
  1613.     char **p_name;
  1614.     char *buf;
  1615.     int *p_buflen;
  1616. {
  1617.     char *name = *p_name;
  1618.     char *dot = strchr(name, '.');
  1619.     int len;
  1620.     char *p;
  1621.     PyObject *result;
  1622.  
  1623.     if (dot == NULL) {
  1624.         *p_name = NULL;
  1625.         len = strlen(name);
  1626.     }
  1627.     else {
  1628.         *p_name = dot+1;
  1629.         len = dot-name;
  1630.     }
  1631.     if (len == 0) {
  1632.         PyErr_SetString(PyExc_ValueError,
  1633.                 "Empty module name");
  1634.         return NULL;
  1635.     }
  1636.  
  1637.     p = buf + *p_buflen;
  1638.     if (p != buf)
  1639.         *p++ = '.';
  1640.     if (p+len-buf >= MAXPATHLEN) {
  1641.         PyErr_SetString(PyExc_ValueError,
  1642.                 "Module name too long");
  1643.         return NULL;
  1644.     }
  1645.     strncpy(p, name, len);
  1646.     p[len] = '\0';
  1647.     *p_buflen = p+len-buf;
  1648.  
  1649.     result = import_submodule(mod, p, buf);
  1650.     if (result == Py_None && altmod != mod) {
  1651.         Py_DECREF(result);
  1652.         /* Here, altmod must be None and mod must not be None */
  1653.         result = import_submodule(altmod, p, p);
  1654.         if (result != NULL && result != Py_None) {
  1655.             if (mark_miss(buf) != 0) {
  1656.                 Py_DECREF(result);
  1657.                 return NULL;
  1658.             }
  1659.             strncpy(buf, name, len);
  1660.             buf[len] = '\0';
  1661.             *p_buflen = len;
  1662.         }
  1663.     }
  1664.     if (result == NULL)
  1665.         return NULL;
  1666.  
  1667.     if (result == Py_None) {
  1668.         Py_DECREF(result);
  1669.         PyErr_Format(PyExc_ImportError,
  1670.                  "No module named %.200s", name);
  1671.         return NULL;
  1672.     }
  1673.  
  1674.     return result;
  1675. }
  1676.  
  1677. static int
  1678. mark_miss(name)
  1679.     char *name;
  1680. {
  1681.     PyObject *modules = PyImport_GetModuleDict();
  1682.     return PyDict_SetItemString(modules, name, Py_None);
  1683. }
  1684.  
  1685. static int
  1686. ensure_fromlist(mod, fromlist, buf, buflen, recursive)
  1687.     PyObject *mod;
  1688.     PyObject *fromlist;
  1689.     char *buf;
  1690.     int buflen;
  1691.     int recursive;
  1692. {
  1693.     int i;
  1694.  
  1695.     if (!PyObject_HasAttrString(mod, "__path__"))
  1696.         return 1;
  1697.  
  1698.     for (i = 0; ; i++) {
  1699.         PyObject *item = PySequence_GetItem(fromlist, i);
  1700.         int hasit;
  1701.         if (item == NULL) {
  1702.             if (PyErr_ExceptionMatches(PyExc_IndexError)) {
  1703.                 PyErr_Clear();
  1704.                 return 1;
  1705.             }
  1706.             return 0;
  1707.         }
  1708.         if (!PyString_Check(item)) {
  1709.             PyErr_SetString(PyExc_TypeError,
  1710.                     "Item in ``from list'' not a string");
  1711.             Py_DECREF(item);
  1712.             return 0;
  1713.         }
  1714.         if (PyString_AS_STRING(item)[0] == '*') {
  1715.             PyObject *all;
  1716.             Py_DECREF(item);
  1717.             /* See if the package defines __all__ */
  1718.             if (recursive)
  1719.                 continue; /* Avoid endless recursion */
  1720.             all = PyObject_GetAttrString(mod, "__all__");
  1721.             if (all == NULL)
  1722.                 PyErr_Clear();
  1723.             else {
  1724.                 if (!ensure_fromlist(mod, all, buf, buflen, 1))
  1725.                     return 0;
  1726.                 Py_DECREF(all);
  1727.             }
  1728.             continue;
  1729.         }
  1730.         hasit = PyObject_HasAttr(mod, item);
  1731.         if (!hasit) {
  1732.             char *subname = PyString_AS_STRING(item);
  1733.             PyObject *submod;
  1734.             char *p;
  1735.             if (buflen + strlen(subname) >= MAXPATHLEN) {
  1736.                 PyErr_SetString(PyExc_ValueError,
  1737.                         "Module name too long");
  1738.                 Py_DECREF(item);
  1739.                 return 0;
  1740.             }
  1741.             p = buf + buflen;
  1742.             *p++ = '.';
  1743.             strcpy(p, subname);
  1744.             submod = import_submodule(mod, subname, buf);
  1745.             Py_XDECREF(submod);
  1746.             if (submod == NULL) {
  1747.                 Py_DECREF(item);
  1748.                 return 0;
  1749.             }
  1750.         }
  1751.         Py_DECREF(item);
  1752.     }
  1753.  
  1754.     /* NOTREACHED */
  1755. }
  1756.  
  1757. static PyObject *
  1758. import_submodule(mod, subname, fullname)
  1759.     PyObject *mod; /* May be None */
  1760.     char *subname;
  1761.     char *fullname;
  1762. {
  1763.     PyObject *modules = PyImport_GetModuleDict();
  1764.     PyObject *m;
  1765.  
  1766.     /* Require:
  1767.        if mod == None: subname == fullname
  1768.        else: mod.__name__ + "." + subname == fullname
  1769.     */
  1770.  
  1771.     if ((m = PyDict_GetItemString(modules, fullname)) != NULL) { 
  1772.         Py_INCREF(m);
  1773.     }
  1774.     else {
  1775.         PyObject *path;
  1776.         char buf[MAXPATHLEN+1];
  1777.         struct filedescr *fdp;
  1778.         FILE *fp = NULL;
  1779.  
  1780.         if (mod == Py_None)
  1781.             path = NULL;
  1782.         else {
  1783.             path = PyObject_GetAttrString(mod, "__path__");
  1784.             if (path == NULL) {
  1785.                 PyErr_Clear();
  1786.                 Py_INCREF(Py_None);
  1787.                 return Py_None;
  1788.             }
  1789.         }
  1790.  
  1791.         buf[0] = '\0';
  1792.         fdp = find_module(subname, path, buf, MAXPATHLEN+1, &fp);
  1793.         Py_XDECREF(path);
  1794.         if (fdp == NULL) {
  1795.             if (!PyErr_ExceptionMatches(PyExc_ImportError))
  1796.                 return NULL;
  1797.             PyErr_Clear();
  1798.             Py_INCREF(Py_None);
  1799.             return Py_None;
  1800.         }
  1801.         m = load_module(fullname, fp, buf, fdp->type);
  1802.         if (fp)
  1803.             fclose(fp);
  1804.         if (m != NULL && mod != Py_None) {
  1805.             if (PyObject_SetAttrString(mod, subname, m) < 0) {
  1806.                 Py_DECREF(m);
  1807.                 m = NULL;
  1808.             }
  1809.         }
  1810.     }
  1811.  
  1812.     return m;
  1813. }
  1814.  
  1815.  
  1816. /* Re-import a module of any kind and return its module object, WITH
  1817.    INCREMENTED REFERENCE COUNT */
  1818.  
  1819. PyObject *
  1820. PyImport_ReloadModule(m)
  1821.     PyObject *m;
  1822. {
  1823.     PyObject *modules = PyImport_GetModuleDict();
  1824.     PyObject *path = NULL;
  1825.     char *name, *subname;
  1826.     char buf[MAXPATHLEN+1];
  1827.     struct filedescr *fdp;
  1828.     FILE *fp = NULL;
  1829.  
  1830.     if (m == NULL || !PyModule_Check(m)) {
  1831.         PyErr_SetString(PyExc_TypeError,
  1832.                 "reload() argument must be module");
  1833.         return NULL;
  1834.     }
  1835.     name = PyModule_GetName(m);
  1836.     if (name == NULL)
  1837.         return NULL;
  1838.     if (m != PyDict_GetItemString(modules, name)) {
  1839.         PyErr_Format(PyExc_ImportError,
  1840.                  "reload(): module %.200s not in sys.modules",
  1841.                  name);
  1842.         return NULL;
  1843.     }
  1844.     subname = strrchr(name, '.');
  1845.     if (subname == NULL)
  1846.         subname = name;
  1847.     else {
  1848.         PyObject *parentname, *parent;
  1849.         parentname = PyString_FromStringAndSize(name, (subname-name));
  1850.         if (parentname == NULL)
  1851.             return NULL;
  1852.         parent = PyDict_GetItem(modules, parentname);
  1853.         Py_DECREF(parentname);
  1854.         if (parent == NULL) {
  1855.             PyErr_Format(PyExc_ImportError,
  1856.                 "reload(): parent %.200s not in sys.modules",
  1857.                 name);
  1858.             return NULL;
  1859.         }
  1860.         subname++;
  1861.         path = PyObject_GetAttrString(parent, "__path__");
  1862.         if (path == NULL)
  1863.             PyErr_Clear();
  1864.     }
  1865.     buf[0] = '\0';
  1866.     fdp = find_module(subname, path, buf, MAXPATHLEN+1, &fp);
  1867.     Py_XDECREF(path);
  1868.     if (fdp == NULL)
  1869.         return NULL;
  1870.     m = load_module(name, fp, buf, fdp->type);
  1871.     if (fp)
  1872.         fclose(fp);
  1873.     return m;
  1874. }
  1875.  
  1876.  
  1877. /* Higher-level import emulator which emulates the "import" statement
  1878.    more accurately -- it invokes the __import__() function from the
  1879.    builtins of the current globals.  This means that the import is
  1880.    done using whatever import hooks are installed in the current
  1881.    environment, e.g. by "rexec".
  1882.    A dummy list ["__doc__"] is passed as the 4th argument so that
  1883.    e.g. PyImport_Import(PyString_FromString("win32com.client.gencache"))
  1884.    will return <module "gencache"> instead of <module "win32com">. */
  1885.  
  1886. PyObject *
  1887. PyImport_Import(module_name)
  1888.     PyObject *module_name;
  1889. {
  1890.     static PyObject *silly_list = NULL;
  1891.     static PyObject *builtins_str = NULL;
  1892.     static PyObject *import_str = NULL;
  1893.     static PyObject *standard_builtins = NULL;
  1894.     PyObject *globals = NULL;
  1895.     PyObject *import = NULL;
  1896.     PyObject *builtins = NULL;
  1897.     PyObject *r = NULL;
  1898.  
  1899.     /* Initialize constant string objects */
  1900.     if (silly_list == NULL) {
  1901.         import_str = PyString_InternFromString("__import__");
  1902.         if (import_str == NULL)
  1903.             return NULL;
  1904.         builtins_str = PyString_InternFromString("__builtins__");
  1905.         if (builtins_str == NULL)
  1906.             return NULL;
  1907.         silly_list = Py_BuildValue("[s]", "__doc__");
  1908.         if (silly_list == NULL)
  1909.             return NULL;
  1910.     }
  1911.  
  1912.     /* Get the builtins from current globals */
  1913.     globals = PyEval_GetGlobals();
  1914.     if(globals != NULL) {
  1915.             Py_INCREF(globals);
  1916.         builtins = PyObject_GetItem(globals, builtins_str);
  1917.         if (builtins == NULL)
  1918.             goto err;
  1919.     }
  1920.     else {
  1921.         /* No globals -- use standard builtins, and fake globals */
  1922.         PyErr_Clear();
  1923.  
  1924.         if (standard_builtins == NULL) {
  1925.             standard_builtins =
  1926.                 PyImport_ImportModule("__builtin__");
  1927.             if (standard_builtins == NULL)
  1928.                 return NULL;
  1929.         }
  1930.  
  1931.         builtins = standard_builtins;
  1932.         Py_INCREF(builtins);
  1933.         globals = Py_BuildValue("{OO}", builtins_str, builtins);
  1934.         if (globals == NULL)
  1935.             goto err;
  1936.     }
  1937.  
  1938.     /* Get the __import__ function from the builtins */
  1939.     if (PyDict_Check(builtins))
  1940.         import=PyObject_GetItem(builtins, import_str);
  1941.     else
  1942.         import=PyObject_GetAttr(builtins, import_str);
  1943.     if (import == NULL)
  1944.         goto err;
  1945.  
  1946.     /* Call the _import__ function with the proper argument list */
  1947.     r = PyObject_CallFunction(import, "OOOO",
  1948.                   module_name, globals, globals, silly_list);
  1949.  
  1950.   err:
  1951.     Py_XDECREF(globals);
  1952.     Py_XDECREF(builtins);
  1953.     Py_XDECREF(import);
  1954.  
  1955.     return r;
  1956. }
  1957.  
  1958.  
  1959. /* Module 'imp' provides Python access to the primitives used for
  1960.    importing modules.
  1961. */
  1962.  
  1963. static PyObject *
  1964. imp_get_magic(self, args)
  1965.     PyObject *self;
  1966.     PyObject *args;
  1967. {
  1968.     char buf[4];
  1969.  
  1970.     if (!PyArg_ParseTuple(args, ""))
  1971.         return NULL;
  1972.     buf[0] = (char) ((MAGIC >>  0) & 0xff);
  1973.     buf[1] = (char) ((MAGIC >>  8) & 0xff);
  1974.     buf[2] = (char) ((MAGIC >> 16) & 0xff);
  1975.     buf[3] = (char) ((MAGIC >> 24) & 0xff);
  1976.  
  1977.     return PyString_FromStringAndSize(buf, 4);
  1978. }
  1979.  
  1980. static PyObject *
  1981. imp_get_suffixes(self, args)
  1982.     PyObject *self;
  1983.     PyObject *args;
  1984. {
  1985.     PyObject *list;
  1986.     struct filedescr *fdp;
  1987.  
  1988.     if (!PyArg_ParseTuple(args, ""))
  1989.         return NULL;
  1990.     list = PyList_New(0);
  1991.     if (list == NULL)
  1992.         return NULL;
  1993.     for (fdp = _PyImport_Filetab; fdp->suffix != NULL; fdp++) {
  1994.         PyObject *item = Py_BuildValue("ssi",
  1995.                        fdp->suffix, fdp->mode, fdp->type);
  1996.         if (item == NULL) {
  1997.             Py_DECREF(list);
  1998.             return NULL;
  1999.         }
  2000.         if (PyList_Append(list, item) < 0) {
  2001.             Py_DECREF(list);
  2002.             Py_DECREF(item);
  2003.             return NULL;
  2004.         }
  2005.         Py_DECREF(item);
  2006.     }
  2007.     return list;
  2008. }
  2009.  
  2010. static PyObject *
  2011. call_find_module(name, path)
  2012.     char *name;
  2013.     PyObject *path; /* list or None or NULL */
  2014. {
  2015.     extern int fclose Py_PROTO((FILE *));
  2016.     PyObject *fob, *ret;
  2017.     struct filedescr *fdp;
  2018.     char pathname[MAXPATHLEN+1];
  2019.     FILE *fp = NULL;
  2020.  
  2021.     pathname[0] = '\0';
  2022.     if (path == Py_None)
  2023.         path = NULL;
  2024.     fdp = find_module(name, path, pathname, MAXPATHLEN+1, &fp);
  2025.     if (fdp == NULL)
  2026.         return NULL;
  2027.     if (fp != NULL) {
  2028.         fob = PyFile_FromFile(fp, pathname, fdp->mode, fclose);
  2029.         if (fob == NULL) {
  2030.             fclose(fp);
  2031.             return NULL;
  2032.         }
  2033.     }
  2034.     else {
  2035.         fob = Py_None;
  2036.         Py_INCREF(fob);
  2037.     }        
  2038.     ret = Py_BuildValue("Os(ssi)",
  2039.               fob, pathname, fdp->suffix, fdp->mode, fdp->type);
  2040.     Py_DECREF(fob);
  2041.     return ret;
  2042. }
  2043.  
  2044. static PyObject *
  2045. imp_find_module(self, args)
  2046.     PyObject *self;
  2047.     PyObject *args;
  2048. {
  2049.     char *name;
  2050.     PyObject *path = NULL;
  2051.     if (!PyArg_ParseTuple(args, "s|O", &name, &path))
  2052.         return NULL;
  2053.     return call_find_module(name, path);
  2054. }
  2055.  
  2056. static PyObject *
  2057. imp_init_builtin(self, args)
  2058.     PyObject *self;
  2059.     PyObject *args;
  2060. {
  2061.     char *name;
  2062.     int ret;
  2063.     PyObject *m;
  2064.     if (!PyArg_ParseTuple(args, "s", &name))
  2065.         return NULL;
  2066.     ret = init_builtin(name);
  2067.     if (ret < 0)
  2068.         return NULL;
  2069.     if (ret == 0) {
  2070.         Py_INCREF(Py_None);
  2071.         return Py_None;
  2072.     }
  2073.     m = PyImport_AddModule(name);
  2074.     Py_XINCREF(m);
  2075.     return m;
  2076. }
  2077.  
  2078. static PyObject *
  2079. imp_init_frozen(self, args)
  2080.     PyObject *self;
  2081.     PyObject *args;
  2082. {
  2083.     char *name;
  2084.     int ret;
  2085.     PyObject *m;
  2086.     if (!PyArg_ParseTuple(args, "s", &name))
  2087.         return NULL;
  2088.     ret = PyImport_ImportFrozenModule(name);
  2089.     if (ret < 0)
  2090.         return NULL;
  2091.     if (ret == 0) {
  2092.         Py_INCREF(Py_None);
  2093.         return Py_None;
  2094.     }
  2095.     m = PyImport_AddModule(name);
  2096.     Py_XINCREF(m);
  2097.     return m;
  2098. }
  2099.  
  2100. static PyObject *
  2101. imp_get_frozen_object(self, args)
  2102.     PyObject *self;
  2103.     PyObject *args;
  2104. {
  2105.     char *name;
  2106.  
  2107.     if (!PyArg_ParseTuple(args, "s", &name))
  2108.         return NULL;
  2109.     return get_frozen_object(name);
  2110. }
  2111.  
  2112. static PyObject *
  2113. imp_is_builtin(self, args)
  2114.     PyObject *self;
  2115.     PyObject *args;
  2116. {
  2117.     char *name;
  2118.     if (!PyArg_ParseTuple(args, "s", &name))
  2119.         return NULL;
  2120.     return PyInt_FromLong(is_builtin(name));
  2121. }
  2122.  
  2123. static PyObject *
  2124. imp_is_frozen(self, args)
  2125.     PyObject *self;
  2126.     PyObject *args;
  2127. {
  2128.     char *name;
  2129.     struct _frozen *p;
  2130.     if (!PyArg_ParseTuple(args, "s", &name))
  2131.         return NULL;
  2132.     p = find_frozen(name);
  2133.     return PyInt_FromLong((long) (p == NULL ? 0 : p->size));
  2134. }
  2135.  
  2136. static FILE *
  2137. get_file(pathname, fob, mode)
  2138.     char *pathname;
  2139.     PyObject *fob;
  2140.     char *mode;
  2141. {
  2142.     FILE *fp;
  2143.     if (fob == NULL) {
  2144.         fp = fopen(pathname, mode);
  2145.         if (fp == NULL)
  2146.             PyErr_SetFromErrno(PyExc_IOError);
  2147.     }
  2148.     else {
  2149.         fp = PyFile_AsFile(fob);
  2150.         if (fp == NULL)
  2151.             PyErr_SetString(PyExc_ValueError,
  2152.                     "bad/closed file object");
  2153.     }
  2154.     return fp;
  2155. }
  2156.  
  2157. static PyObject *
  2158. imp_load_compiled(self, args)
  2159.     PyObject *self;
  2160.     PyObject *args;
  2161. {
  2162.     char *name;
  2163.     char *pathname;
  2164.     PyObject *fob = NULL;
  2165.     PyObject *m;
  2166.     FILE *fp;
  2167.     if (!PyArg_ParseTuple(args, "ss|O!", &name, &pathname,
  2168.                   &PyFile_Type, &fob))
  2169.         return NULL;
  2170.     fp = get_file(pathname, fob, "rb");
  2171.     if (fp == NULL)
  2172.         return NULL;
  2173.     m = load_compiled_module(name, pathname, fp);
  2174.     if (fob == NULL)
  2175.         fclose(fp);
  2176.     return m;
  2177. }
  2178.  
  2179. static PyObject *
  2180. imp_load_dynamic(self, args)
  2181.     PyObject *self;
  2182.     PyObject *args;
  2183. {
  2184.     char *name;
  2185.     char *pathname;
  2186.     PyObject *fob = NULL;
  2187.     PyObject *m;
  2188.     FILE *fp = NULL;
  2189.     if (!PyArg_ParseTuple(args, "ss|O!", &name, &pathname,
  2190.                   &PyFile_Type, &fob))
  2191.         return NULL;
  2192.     if (fob) {
  2193.         fp = get_file(pathname, fob, "r");
  2194.         if (fp == NULL)
  2195.             return NULL;
  2196.     }
  2197.     m = _PyImport_LoadDynamicModule(name, pathname, fp);
  2198.     return m;
  2199. }
  2200.  
  2201. static PyObject *
  2202. imp_load_source(self, args)
  2203.     PyObject *self;
  2204.     PyObject *args;
  2205. {
  2206.     char *name;
  2207.     char *pathname;
  2208.     PyObject *fob = NULL;
  2209.     PyObject *m;
  2210.     FILE *fp;
  2211.     if (!PyArg_ParseTuple(args, "ss|O!", &name, &pathname,
  2212.                   &PyFile_Type, &fob))
  2213.         return NULL;
  2214.     fp = get_file(pathname, fob, "r");
  2215.     if (fp == NULL)
  2216.         return NULL;
  2217.     m = load_source_module(name, pathname, fp);
  2218.     if (fob == NULL)
  2219.         fclose(fp);
  2220.     return m;
  2221. }
  2222.  
  2223. #ifdef macintosh
  2224. static PyObject *
  2225. imp_load_resource(self, args)
  2226.     PyObject *self;
  2227.     PyObject *args;
  2228. {
  2229.     char *name;
  2230.     char *pathname;
  2231.     PyObject *m;
  2232.  
  2233.     if (!PyArg_ParseTuple(args, "ss", &name, &pathname))
  2234.         return NULL;
  2235.     m = PyMac_LoadResourceModule(name, pathname);
  2236.     return m;
  2237. }
  2238. #endif /* macintosh */
  2239.  
  2240. static PyObject *
  2241. imp_load_module(self, args)
  2242.     PyObject *self;
  2243.     PyObject *args;
  2244. {
  2245.     char *name;
  2246.     PyObject *fob;
  2247.     char *pathname;
  2248.     char *suffix; /* Unused */
  2249.     char *mode;
  2250.     int type;
  2251.     FILE *fp;
  2252.  
  2253.     if (!PyArg_ParseTuple(args, "sOs(ssi)",
  2254.                   &name, &fob, &pathname,
  2255.                   &suffix, &mode, &type))
  2256.         return NULL;
  2257.     if (*mode && (*mode != 'r' || strchr(mode, '+') != NULL)) {
  2258.         PyErr_Format(PyExc_ValueError,
  2259.                  "invalid file open mode %.200s", mode);
  2260.         return NULL;
  2261.     }
  2262.     if (fob == Py_None)
  2263.         fp = NULL;
  2264.     else {
  2265.         if (!PyFile_Check(fob)) {
  2266.             PyErr_SetString(PyExc_ValueError,
  2267.                 "load_module arg#2 should be a file or None");
  2268.             return NULL;
  2269.         }
  2270.         fp = get_file(pathname, fob, mode);
  2271.         if (fp == NULL)
  2272.             return NULL;
  2273.     }
  2274.     return load_module(name, fp, pathname, type);
  2275. }
  2276.  
  2277. static PyObject *
  2278. imp_load_package(self, args)
  2279.     PyObject *self;
  2280.     PyObject *args;
  2281. {
  2282.     char *name;
  2283.     char *pathname;
  2284.     if (!PyArg_ParseTuple(args, "ss", &name, &pathname))
  2285.         return NULL;
  2286.     return load_package(name, pathname);
  2287. }
  2288.  
  2289. static PyObject *
  2290. imp_new_module(self, args)
  2291.     PyObject *self;
  2292.     PyObject *args;
  2293. {
  2294.     char *name;
  2295.     if (!PyArg_ParseTuple(args, "s", &name))
  2296.         return NULL;
  2297.     return PyModule_New(name);
  2298. }
  2299.  
  2300. /* Doc strings */
  2301.  
  2302. static char doc_imp[] = "\
  2303. This module provides the components needed to build your own\n\
  2304. __import__ function.  Undocumented functions are obsolete.\n\
  2305. ";
  2306.  
  2307. static char doc_find_module[] = "\
  2308. find_module(name, [path]) -> (file, filename, (suffix, mode, type))\n\
  2309. Search for a module.  If path is omitted or None, search for a\n\
  2310. built-in, frozen or special module and continue search in sys.path.\n\
  2311. The module name cannot contain '.'; to search for a submodule of a\n\
  2312. package, pass the submodule name and the package's __path__.\
  2313. ";
  2314.  
  2315. static char doc_load_module[] = "\
  2316. load_module(name, file, filename, (suffix, mode, type)) -> module\n\
  2317. Load a module, given information returned by find_module().\n\
  2318. The module name must include the full package name, if any.\
  2319. ";
  2320.  
  2321. static char doc_get_magic[] = "\
  2322. get_magic() -> string\n\
  2323. Return the magic number for .pyc or .pyo files.\
  2324. ";
  2325.  
  2326. static char doc_get_suffixes[] = "\
  2327. get_suffixes() -> [(suffix, mode, type), ...]\n\
  2328. Return a list of (suffix, mode, type) tuples describing the files\n\
  2329. that find_module() looks for.\
  2330. ";
  2331.  
  2332. static char doc_new_module[] = "\
  2333. new_module(name) -> module\n\
  2334. Create a new module.  Do not enter it in sys.modules.\n\
  2335. The module name must include the full package name, if any.\
  2336. ";
  2337.  
  2338. static PyMethodDef imp_methods[] = {
  2339.     {"find_module",        imp_find_module,    1, doc_find_module},
  2340.     {"get_magic",        imp_get_magic,        1, doc_get_magic},
  2341.     {"get_suffixes",    imp_get_suffixes,    1, doc_get_suffixes},
  2342.     {"load_module",        imp_load_module,    1, doc_load_module},
  2343.     {"new_module",        imp_new_module,        1, doc_new_module},
  2344.     /* The rest are obsolete */
  2345.     {"get_frozen_object",    imp_get_frozen_object,    1},
  2346.     {"init_builtin",    imp_init_builtin,    1},
  2347.     {"init_frozen",        imp_init_frozen,    1},
  2348.     {"is_builtin",        imp_is_builtin,        1},
  2349.     {"is_frozen",        imp_is_frozen,        1},
  2350.     {"load_compiled",    imp_load_compiled,    1},
  2351.     {"load_dynamic",    imp_load_dynamic,    1},
  2352.     {"load_package",    imp_load_package,    1},
  2353. #ifdef macintosh
  2354.     {"load_resource",    imp_load_resource,    1},
  2355. #endif
  2356.     {"load_source",        imp_load_source,    1},
  2357.     {NULL,            NULL}        /* sentinel */
  2358. };
  2359.  
  2360. static int
  2361. setint(d, name, value)
  2362.     PyObject *d;
  2363.     char *name;
  2364.     int value;
  2365. {
  2366.     PyObject *v;
  2367.     int err;
  2368.  
  2369.     v = PyInt_FromLong((long)value);
  2370.     err = PyDict_SetItemString(d, name, v);
  2371.     Py_XDECREF(v);
  2372.     return err;
  2373. }
  2374.  
  2375. void
  2376. initimp()
  2377. {
  2378.     PyObject *m, *d;
  2379.  
  2380.     m = Py_InitModule4("imp", imp_methods, doc_imp,
  2381.                NULL, PYTHON_API_VERSION);
  2382.     d = PyModule_GetDict(m);
  2383.  
  2384.     if (setint(d, "SEARCH_ERROR", SEARCH_ERROR) < 0) goto failure;
  2385.     if (setint(d, "PY_SOURCE", PY_SOURCE) < 0) goto failure;
  2386.     if (setint(d, "PY_COMPILED", PY_COMPILED) < 0) goto failure;
  2387.     if (setint(d, "C_EXTENSION", C_EXTENSION) < 0) goto failure;
  2388.     if (setint(d, "PY_RESOURCE", PY_RESOURCE) < 0) goto failure;
  2389.     if (setint(d, "PKG_DIRECTORY", PKG_DIRECTORY) < 0) goto failure;
  2390.     if (setint(d, "C_BUILTIN", C_BUILTIN) < 0) goto failure;
  2391.     if (setint(d, "PY_FROZEN", PY_FROZEN) < 0) goto failure;
  2392.     if (setint(d, "PY_CODERESOURCE", PY_CODERESOURCE) < 0) goto failure;
  2393.  
  2394.   failure:
  2395.     ;
  2396. }
  2397.  
  2398.  
  2399. /* API for embedding applications that want to add their own entries to the
  2400.    table of built-in modules.  This should normally be called *before*
  2401.    Py_Initialize().  When the malloc() or realloc() call fails, -1 is returned
  2402.    and the existing table is unchanged.
  2403.  
  2404.    After a similar function by Just van Rossum. */
  2405.  
  2406. int
  2407. PyImport_ExtendInittab(newtab)
  2408.     struct _inittab *newtab;
  2409. {
  2410.     static struct _inittab *our_copy = NULL;
  2411.     struct _inittab *p;
  2412.     int i, n;
  2413.  
  2414.     /* Count the number of entries in both tables */
  2415.     for (n = 0; newtab[n].name != NULL; n++)
  2416.         ;
  2417.     if (n == 0)
  2418.         return 0; /* Nothing to do */
  2419.     for (i = 0; PyImport_Inittab[i].name != NULL; i++)
  2420.         ;
  2421.  
  2422.     /* Allocate new memory for the combined table */
  2423.     if (our_copy == NULL)
  2424.         p = malloc((i+n+1) * sizeof(struct _inittab));
  2425.     else
  2426.         p = realloc(our_copy, (i+n+1) * sizeof(struct _inittab));
  2427.     if (p == NULL)
  2428.         return -1;
  2429.  
  2430.     /* Copy the tables into the new memory */
  2431.     if (our_copy != PyImport_Inittab)
  2432.         memcpy(p, PyImport_Inittab, (i+1) * sizeof(struct _inittab));
  2433.     PyImport_Inittab = our_copy = p;
  2434.     memcpy(p+i, newtab, (n+1) * sizeof(struct _inittab));
  2435.  
  2436.     return 0;
  2437. }
  2438.  
  2439. /* Shorthand to add a single entry given a name and a function */
  2440.  
  2441. int
  2442. PyImport_AppendInittab(name, initfunc)
  2443.     char *name;
  2444.     void (*initfunc)();
  2445. {
  2446.     struct _inittab newtab[2];
  2447.  
  2448.     memset(newtab, '\0', sizeof newtab);
  2449.  
  2450.     newtab[0].name = name;
  2451.     newtab[0].initfunc = initfunc;
  2452.  
  2453.     return PyImport_ExtendInittab(newtab);
  2454. }
  2455.